package com.heny.demo.dbutils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

/**
 * @author litao.cc
 * @version DeviceDataTableCreator.java v0.1 t2025/5/5 21:25
 * @date 2025/5/5 21:25
 * @description 设备统计数据表创建
 */
@Service("deviceDataTableCreator")
public class DeviceDataTableCreator implements TableCreator{

    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Override
    public void createTableIfAbsent(DynamicTableProcessorEnum t, DynamicTableModel p) {
        String tableName = t.getProcessor().getTableName(p);
        String checkSql = String.format(
                "SELECT to_regclass('%s') IS NOT NULL AS exists;",
                tableName
        );
        String res = jdbcTemplate.queryForObject(checkSql, String.class);
        if(res.equals("f")){
            // TODO 假设只有一个key值,当然这个模板值需要从配置中取,关联物模型中配置的字段
            String createSql = 
                    "CREATE TABLE tableName ( " +
                            "    id SERIAL PRIMARY KEY,                      " +
                            "    dev_id BIGINT NOT NULL,                     " +
                            "    sn VARCHAR(255) NOT NULL,                   " +
                            "    time BIGINT NOT NULL,                       " +
                            "    aggregation_type VARCHAR(255),              " +
                            "    key1 float4,                                " +
                            "    created_at TIMESTAMP WITH TIME ZONE         " +
                            "); " +
                            " " +
                            "COMMENT ON TABLE tableName IS '设备小时数据表'; " +
                            "COMMENT ON COLUMN tableName.id IS '主键ID'; " +
                            "COMMENT ON COLUMN tableName.dev_id IS '设备编号'; " +
                            "COMMENT ON COLUMN tableName.sn IS '设备SN号'; " +
                            "COMMENT ON COLUMN tableName.time IS '时间'; " +
                            "COMMENT ON COLUMN tableName.aggregation_type IS '聚合方法'; " +
                            "COMMENT ON COLUMN tableName.key1 IS '数据1'; " +
                            "COMMENT ON COLUMN tableName.created_at IS '创建时间';";
            jdbcTemplate.execute(createSql.replaceAll("tableName", tableName));
        }


    }
}
